package com.lvhx.springboot.springbatch.readfile;

import com.lvhx.springboot.entity.User;
import org.apache.commons.io.FileUtils;
import org.springframework.batch.core.annotation.OnSkipInRead;
import org.springframework.batch.core.annotation.OnSkipInWrite;
import org.springframework.batch.item.file.FlatFileParseException;

import java.io.File;
import java.io.IOException;

/**
 * @auther 吕宏旭
 * @date 2019/9/5 11:09
 */
public class FileSkipListener {

    private File file = new File("classpath:log.txt");

    public FileSkipListener(File file) {
        file = new File("log.txt");
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        this.file = file;
    }

    @OnSkipInRead
    public void readLog(Throwable t) throws IOException {
        if (t instanceof FlatFileParseException) {
            FlatFileParseException ffpe = (FlatFileParseException) t;
            String dataLog = "from read " + ffpe.getInput() + ", line number = " + ffpe.getLineNumber() + "\n";
            FileUtils.write(file, dataLog, true);
        }
    }

    @OnSkipInWrite
    public void wirteLog(User user, Throwable t) throws IOException {
        if (t instanceof FlatFileParseException) {
            FlatFileParseException ffpe = (FlatFileParseException) t;

            String dataLog = "from write " + ffpe.getInput() + ", line number = " + ffpe.getLineNumber() + "\n";
            String userInfo = user.getName() + ", address " + user.getPassword() + "\n";

            FileUtils.write(file, dataLog + userInfo, true);
        }
    }

}
